package org.zn.note.designpattern;

/**
 * 组合实体模式（Composite Entity Pattern）
 */
public class Pattern28_CompositeEntity {

    public static void main(String[] args) {
        Client client = new Client();
        client.setData("Test", "Data");
        client.printData();
        client.setData("Second Test", "Data1");
        client.printData();
    }

    // 依赖对象1
    private static class DependentObject1 {

        private String data;

        void setData(String data) {
            this.data = data;
        }

        String getData() {
            return data;
        }
    }

    private static class DependentObject2 {

        private String data;

        void setData(String data) {
            this.data = data;
        }

        String getData() {
            return data;
        }
    }

    // 粗粒度对象
    private static class CoarseGrainedObject {
        DependentObject1 do1 = new DependentObject1();
        DependentObject2 do2 = new DependentObject2();

        void setData(String data1, String data2) {
            do1.setData(data1);
            do2.setData(data2);
        }

        String[] getData() {
            return new String[]{do1.getData(), do2.getData()};
        }
    }

    // 组合实体
    private static class CompositeEntity {
        private CoarseGrainedObject cgo = new CoarseGrainedObject();

        void setData(String data1, String data2) {
            cgo.setData(data1, data2);
        }

        String[] getData() {
            return cgo.getData();
        }
    }

    // 组合实体客户端
    private static class Client {
        private CompositeEntity compositeEntity = new CompositeEntity();

        void printData() {
            for (int i = 0; i < compositeEntity.getData().length; i++) {
                System.out.println("Data: " + compositeEntity.getData()[i]);
            }
        }

        void setData(String data1, String data2) {
            compositeEntity.setData(data1, data2);
        }
    }
}
